package ru.niir.goodfil.ui;

import ru.niir.goodfil.audit.domain.OrderUIEvent;
import ru.niir.goodfil.audit.domain.enums.OrderUIEventType;
import ru.niir.goodfil.db.Client;
import ru.niir.goodfil.db.Order;
import ru.niir.goodfil.db.User;

public class OrderStatBean extends PageBean {
    private long orderId;
    private int orderState;
    private Order order;

    public void setOrderId(long orderId) {
        this.orderId = orderId;
    }

    public long getOrderId() {
        return orderId;
    }

    public Order getOrder() {
        if (order == null) order = gf().getOrderById(orderId);
        return order;
    }

    public void setOrder(Order order) {
        this.order = order;
    }

    public void setOrderState(int orderState) {
        this.orderState = orderState;
    }

    public int getOrderState() {
        return orderState;
    }

    public void changeOrderState() {
        try {
            Long orderId = getOrder().getId();
            gf().setOrderState_Unsafe(getOrder().getId(), orderState);
            this.order = null;
            facesInfo("Заказ сохранен");

            Order order = gf().getOrderById(orderId);
            gf().addOrderInfo(order);
            getAuditService().logOrderUIEvent(prepareOrderUIEvent(OrderUIEventType.ROLLBACKED, order));
        } catch (Exception e) {
            e.printStackTrace();
            facesError("Ошибка сохранения заказа");
        }
    }

    private OrderUIEvent prepareOrderUIEvent(OrderUIEventType type, Order order) {
        OrderUIEvent event = new OrderUIEvent();

        event.setIp(getAuditHelper().getIp());
        event.setLogin(getAuditHelper().getLogin());
        event.setType(type);

        event.setOrderId(String.valueOf(order.getId()));
        event.setC1Num(order.getC1Num());

        Client client = order.getClient();
        if (client == null) client = gf().getClientById(order.getClientId());
        event.setClientId(String.valueOf(client.getId()));
        event.setClientName(client.getCompanyName());

        User manager = order.getManager();
        if (manager == null) manager = gf().getUserById(order.getManagerId());
        event.setManagerId(String.valueOf(manager.getId()));
        event.setManagerName(manager.getFio());

        event.setCreationDate(order.getCreationDateAsString());
        event.setDeliveryDate(order.getDeliveryDateAsString());
        event.setOrderSum(String.valueOf(order.getSum()));

        return event;
    }
}
